
const fs = require('fs')
const mysql=require('mysql')
const path = require('path')

const Controller_content = {}

//导入模块
const dbQuery = require('../model/model.js')

const {getUnixTime} = require('../util/tool')

//  审核状态
let statusTextMap = {
    0: '<span class="c-gray">待审核</span>',
    1: '<span class="c-green">审核通过</span>',
    2: '<span class="c-red">审核失败</span>'
}

//首页
Controller_content.index=(req, res)=> {
    // 1. 编写sql语句
    
    let userInfo = JSON.parse(req.session.userInfo);
    // console.log(userInfo)
    //连表  指定  排序 
    let sql = `select t1.*,t2.name from article t1 left join articletable t2 on t1.sort = t2.id where is_delete = 0 order by id desc`
    // 2. 执行sql
    dbQuery(sql).then(result => {
        let data = result.map((item) => {
            item.status_text = statusTextMap[item.Audit_status]
            return item;
        })
        // console.log(data)
        // 3. 把查询出来的数据分配到模板引擎中
        // if(userInfo.account_number =="陈鉴彪123"){
        //     userInfo.account_number="伟大的陈鉴彪"
        // }

        res.render('Articlepage.html', { articles: data,userInfo })
    })

}

//文章回收
Controller_content.recyclelist=(req, res) => {
    let userInfo = JSON.parse( req.session.userInfo || '{}' );
    // 1. 编写sql语句
    let sql = `select t1.*,t2.name from article t1 
    left join Articletable t2 on t1.sort = t2.id 
     where t1.Audit_status =1  and t1.is_delete = 1 order by t1.id desc`;
   //执行slq
   dbQuery(sql).then(result=>{
       let data = result.map((item)=>{
           item.status_text = statusTextMap[item.status]
           return item;
       })
       res.render('recycle.html',{articles:data,userInfo})
   })
}

//  4 文章删除
Controller_content.delete = (req, res) => {
    //1. 接受要删除的文章的id
    let { id,img} = req.query;
    
    //2. 编写sql语句，删除
    let sql = `delete from article where id = ${id}`;
    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            if(img){
                let oldpath = path.join(__dirname,'../',img)
                fs.unlink(oldpath,(err)=>{

                })
            }
            // 删除成功 ，重定向到首页
            res.redirect('Articlepage')
        } else {
            // 删除失败，响应js代码，让浏览器执行
            res.send("<script>alert('删除失败'); location.href = '/'; </script>")
        }
    })

}


//   ajax文章删除
Controller_content.ajaxdelete = (req, res) => {
    //1. 接受要删除的文章的id
    let { id,img} = req.body;
    //2. 编写sql语句，删除
    let sql = `delete from article where id = ${id}`;
    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            if(img){
                let oldpath = path.join(__dirname,'../',img)
                fs.unlink(oldpath,(err)=>{

                })
            }
            res.json({
                code:20000,
                message:"succes"
            })
           
        }else{
            res.json({
                code:-1,
                message:"fial"
            })
        }
    })

}

// 5 文章添加
Controller_content.add = (req, res) => {
    let userInfo = JSON.parse( req.session.userInfo || '{}' );
    // 取出所有的分类数据分配到模板中
    let sql = "select * from articletable";
    dbQuery(sql).then(result => {
        res.render('add.html', { cats: result,userInfo })
    })
}

// // 实现数据添加入库 
Controller_content.insert = (req, res) => {
    // //判断是否有图片
    let imgPath = '';
    if(req.file){

        let{originalname,filename,destination} = req.file
        let ext = originalname.substring( originalname.indexOf('.'));

        let oldpath = path.join(__dirname,"../",destination,filename);
        let newPath = path.join(__dirname,"../",destination,filename) + ext;
        imgPath = `${destination}${filename}${ext}`
        fs.renameSync(oldpath,newPath)
    }
    // 1.接受post参数
    let { title, author, cat_id, content, AudIt_status } = req.body
    let nowTime = getUnixTime();
    //  第一个（）中的字段是设计表中的字段，第二个（）是前端传过来字段
    let sql = `insert into article(title,img,author,content,sort,Audit_status,Update_time)values
    ("${title}","${imgPath}","${author}","${content}","${cat_id}","${AudIt_status}","${nowTime}")`;
    // let bind = [title,imgPath,author,content,cat_id,AudIt_status,nowTime]

    dbQuery(sql).then(result => {
        // 3.判断结果
        if (result.affectedRows) {
            res.send("<script>alert('成功');location.href='/';</script>")
        } else {
            res.send("<script>alert('失败');location.href='/add';</script>")
        }
    })
}

//  实现编辑文章页面的回显操作
Controller_content.edit = (req, res) => {
    let userInfo = JSON.parse( req.session.userInfo || '{}' );
    let { id } = req.query;
    // 查询指定条件
    let sql = `select * from article where id=${id}`;
    dbQuery(sql).then( result => {
        let sql2 = 'select * from articletable';
        dbQuery(sql2).then(result2 => {
            res.render('edit.html',
             {articles:result[0],
            sort:result2,userInfo})
        })
    })
}

// // 实现文章编辑入库操作
Controller_content.update = (req, res) => {

    let { id, title, author, Audit_status, sort, content } = req.body
    console.log(req.body)
    let Update_time = getUnixTime();

    let sql = `update article set title ="${title}",author ="${author}",Audit_status ="${Audit_status}",sort ="${sort}",content ="${content}",Update_time ="${Update_time}" where id ="${id}"`
    dbQuery(sql).then(result => {
        if (result.affectedRows) {
            res.redirect('/Articlepage')
        } else {
            res.send('<script>alert("编辑失败");location.href="/";<script>')
        }
    })
}

// //实现文章加入回收站
Controller_content.recycle = (req, res) => {
    let { id } = req.query
    $sql = `update article set is_delete = 1 where id =${id}`;
    //执行
    dbQuery($sql).then (result => {
        let { affectedRows } = result;
        //判断剩余行数
        if (affectedRows) {
            res.redirect('/Articlepage')
        } else {
            res.send("<script>alert(加入失败);location.href='/'</script>")

        }
    })
}

// //实现文章还原
Controller_content.restore = (req,res)=>{
    let{ id = 0 } =req.query
    $sql = `update article set is_delete = 0 where id = ${id}`;
    dbQuery($sql).then(result=>{
        let {affectedRows} = result;
        if(affectedRows){
            res.redirect('/Articlepage')
        }else{
            res.send("<script>alert('还原失败');location.href='/';</script>")
        }
    })
}

 //展示一个上传文件的表单
Controller_content.addImg = (req,res)=>{
    res.render('addimg.html')
}

//处理文件上传
Controller_content.upload = (req,res)=>{
    // console.log(req.file); // 接收二进制数据
    // console.log(req.body); 
    let{ originalname,filename,destination} = req.file

    let ext = originalname.substring( originalname.indexOf('.'));

    let oldpath = path.join(__dirname,destination,filename);
    let newPath = path.join(__dirname,destination,filename) + ext;
     fs.renameSync(oldpath,newPath)

     res.send('upload success')
}

//文章详情
Controller_content.detail = (req,res)=>{
    let {id} = req.query;
    // console.log(id)
    let sql = `select * from article where id = ${id}`
    dbQuery(sql).then(result=>{
      
                res.render('detail.html', { a: result[0] })

    })
  
}

module.exports = Controller_content